package com.nervenets.web.controller.handler.user.wealth;

import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.NumberUtil;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.*;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.rabbitmq.FlowMessage;
import com.nervenets.web.redis.domain.global.GlobalRule;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

public class UserReward2MoneyHandler extends Handler<UserReward2MoneyParams> {
    @Override
    public String handle(UserReward2MoneyParams params, HttpServletRequest request) throws Exception {
        if (!globalVariablesService.canProceed(params.getUserId())) return errorMessage(MessageCode.code_505);

        User user = userDao.findById(params.getUserId(), User.class);
        if (null == user) return errorMessage(MessageCode.code_778);

        return (String) redisSyncLocker.keyLock(String.format(Global.Constants.REDIS_USER_WEALTH_LOCK, params.getUserId()), new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                long reward = userDao.getSurplus(params.getUserId(), WealthType.reward);
                if (reward < params.getMoney()) return errorMessage(MessageCode.code_444, "奖励金余额不足");

                final GlobalRule globalRule = globalVariablesService.getGlobalRule();
                BigDecimal proportionOfFee = globalRule.getProportionOfReward2Money();

                final long fee = proportionOfFee.multiply(BigDecimal.valueOf(params.getMoney())).longValue();
                final long realWithdrawMoney = params.getMoney() - fee;

                long unionId = JodaUtils.getTimestamp() + NumberUtil.randomNumber(1000, 9999);//生成提现关联ID
                messageProducer.flow(FlowMessage.rewardChange(params.getUserId(), getIp(request), UnionType.normal, unionId, -fee, OperateType.rewardWithdrawFee, PayType.surplus, FlowStatus.handling, "奖励金提现发票保证金"));
                messageProducer.flow(FlowMessage.rewardChange(params.getUserId(), getIp(request), UnionType.normal, unionId, -realWithdrawMoney, OperateType.rewardWithdraw, PayType.surplus, FlowStatus.success, "奖励金提现"));
                messageProducer.flow(FlowMessage.wealthChange(params.getUserId(), getIp(request), UnionType.normal, unionId, realWithdrawMoney, OperateType.rewardWithdraw, PayType.surplus, FlowStatus.success, "奖励金提现"));

                return successMessage();
            }
        }, null);
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
